package com.lucy.common.aspect;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.extra.servlet.ServletUtil;
import com.lucy.common.anno.FormLock;
import com.lucy.common.constant.HttpStatus;
import com.lucy.common.exception.BusinessException;
import com.lucy.common.redis.RedisCache;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;

/**
 * @author kindear
 */
@Slf4j
@Aspect
@Component
public class FormLockAspect {
    /**
     * 引入Redis 服务
     */
    @Autowired
    RedisCache redisCache;

    /**
     * 以自定义注解作为切入
     */
    @Pointcut("@annotation(com.lucy.common.anno.FormLock)")
    public void FormLock(){}

    @Before("FormLock()")
    public void doBefore(JoinPoint joinPoint) {
        log.debug("拦截表单重复提交");
        //获取当前请求对象
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        // 获取自定义注解信息
        FormLock formLock = method.getAnnotation(FormLock.class);
        // 获取注解中参数
        String lockKey = formLock.lockKey();
        int lockSeconds = formLock.lockSeconds();
        boolean needLogin = formLock.needLogin();
        // 如果是需要登录
        if (needLogin){
            String loginId = StpUtil.getLoginIdAsString();
            Boolean isLocked = redisCache.getCacheObject(lockKey+":"+loginId);
            if (Validator.isNotEmpty(isLocked)){
                throw new BusinessException(HttpStatus.FORBIDDEN,"请不要重复请求");
            }else {
                redisCache.setCacheObject(lockKey+":"+loginId, true, lockSeconds, TimeUnit.SECONDS);
            }
        }else {
            // 如果是不需要登录的条件下
            String clientIP = ServletUtil.getClientIP(request);
            log.info("客户端IP:"+clientIP);
            Boolean isLocked = redisCache.getCacheObject(lockKey+":"+clientIP);
            if (Validator.isNotEmpty(isLocked)){
                throw new BusinessException(HttpStatus.FORBIDDEN,"请不要重复请求");
            }else {
                redisCache.setCacheObject(lockKey+":"+clientIP, true, lockSeconds, TimeUnit.SECONDS);
            }
        }

    }

}
